﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DevExpress.Xpf.Core;
using ThanNhanTao.Server;
using System.Windows.Markup;
using DevExpress.Xpf.Grid;
using DevExpress.Xpf.Editors;
using DevExpress.XtraEditors.DXErrorProvider;
using ThanNhanTao.CommonControl;
using System.Configuration;
using System.Xml;
using System.Data.SqlClient;
using System.Management;
using System.Net;
using System.Data;
using ThanNhanTao.Properties;


namespace ThanNhanTao
{
    /// <summary>
    /// Interaction logic for frmConnecSQL.xaml
    /// </summary>
    public partial class frmConnecSQL : DXWindow
    {
        public bool WasConnected { get; set; }
        public frmConnecSQL()
        {
            try
            {
                InitializeComponent();
                cboserverName.Items.Add(Settings.Default.DATASOURCE);
                txtlogin.Text = Settings.Default.USERNAME;
                txtpass.Text = Settings.Default.PASSWORD;
                cboserverName.SelectedIndex = 0;
            }
            catch (Exception)
            {
                DXMessageBox.Show("Lấy thông tin cấu hình không thành công", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void buttonLuu_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!CheckConnectionServer())
                {
                    DXMessageBox.Show("Kết nối không thành công. \n", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                if (!CheckDuLieuVao())
                {
                    DXMessageBox.Show("Thông tin không đầy đủ.", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                UpdateConfileAppSettings();
            }
            catch(Exception)
            {
                DXMessageBox.Show("Lỗi nội bộ", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #region Ham su dung cho viec cap nhat config tai node appSettings
        /// <summary>
        /// Cap nhat du lieu tuong ung cho tung tham so trong appSettings
        /// </summary>
        private void UpdateConfileAppSettings()
        {
            try
            {
                Settings.Default.DATASOURCE = cboserverName.DisplayText;
                Settings.Default.USERNAME = txtlogin.Text;
                Settings.Default.PASSWORD = txtpass.Text;
                Settings.Default.Save();
                DXMessageBox.Show("Cập nhật thông tin kết nối thành công.","Thông báo", MessageBoxButton.OK, MessageBoxImage.Information);
                ThanNhanTaoGlobalServer.SetConnectionCommon(Settings.Default.DATASOURCE, Settings.Default.DBNAME
                                                                , Settings.Default.USERNAME
                                                                , Settings.Default.PASSWORD
                                                                , ConfigurationManager.ConnectionStrings["bvdn_thannhantaoEntities"].ToString());
                // Save config already after set flag WasConnected = true
                this.WasConnected = true;
            }
            catch(Exception)
            {
                DXMessageBox.Show("Lỗi nội bộ.\nCập nhật thông tin kết nối không thành công.", "Thông báo", MessageBoxButton.OK, MessageBoxImage.Error);
                this.WasConnected = false;
            }
        }

        private string GetComputerName()
        {
            return Dns.GetHostName();
        }

        private bool CheckDuLieuVao()
        {
            if(string.IsNullOrEmpty(cboserverName.DisplayText))
            {
                return false;
            }
            if (string.IsNullOrEmpty(txtlogin.Text))
            {
                return false;
            }
            //if (string.IsNullOrEmpty(cboDataBase.DisplayText))
            //{
            //    return false;
            //}
            return true;
        }

        public bool CheckConnectionServer()
        {
            string myConnect = "Data source=" + cboserverName.DisplayText + ";user id=" + txtlogin.Text + ";password=" + txtpass.Text + ";persist security info=True";
            SqlConnection conn = new SqlConnection(myConnect);
            try
            {
                conn.Open();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }


        #endregion

        #region Ham su dung cho viec cap nhat config tai node connectionStrings
        /// <summary>
        /// tao ra chuoi connection day du
        /// </summary>
        /// <param name="dataSource"></param>
        /// <param name="initialCatalog"></param>
        /// <param name="userId"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        private string CreateConnection(string dataSource, string initialCatalog, string userId, string pass)
        {
            string[] arrayParameter = GetThamSo();
            StringBuilder conecTemple = new StringBuilder();
            try
            {
                for (int i = 0; i < arrayParameter.Count(); i++)
                {
                    if (arrayParameter[i].Contains("data source"))
                    {
                        arrayParameter[i] = "data source=" + dataSource;
                    }
                    if (arrayParameter[i].Contains("Server"))
                    {
                        arrayParameter[i] = "Server=" + dataSource;
                    }

                    if (arrayParameter[i].Contains("initial catalog"))
                    {
                        arrayParameter[i] = "initial catalog=" + initialCatalog;
                    }
                    if (arrayParameter[i].Contains("Database"))
                    {
                        arrayParameter[i] = "Database=" + initialCatalog;
                    }

                    if (arrayParameter[i].Contains("user id"))
                    {
                        arrayParameter[i] = "user id=" + userId;
                    }
                    if (arrayParameter[i].Contains("Uid"))
                    {
                        arrayParameter[i] = "Uid=" + userId;
                    }

                    if (arrayParameter[i].Contains("password"))
                    {
                        arrayParameter[i] = "password=" + pass;
                    }
                    if (arrayParameter[i].Contains("Pwd"))
                    {
                        arrayParameter[i] = "Pwd=" + pass;
                    }
                    conecTemple.Append(arrayParameter[i]);
                    if (!string.IsNullOrEmpty(arrayParameter[i]))
                    {
                        conecTemple.Append(";");
                    }
                }

            }
            catch (Exception)
            {
            }
            return conecTemple.ToString();
        }

        /// <summary>
        /// Lay tham so tu chuoi connection day du
        /// </summary>
        /// <returns></returns>
        private string[] GetThamSo()
        {
            string[] temple = null;
            XmlDocument XmlDoc = new XmlDocument();
            XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in XmlDoc.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    temple = xElement.FirstChild.Attributes[1].Value.Split(';');
                }
            }
            return temple;
        }

        /// <summary>
        /// update chuoi connection day du
        /// </summary>
        /// <param name="connec"></param>
        private void UpdateConfigFile(string connec)
        {
            XmlDocument XmlDoc = new XmlDocument();
            XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
            foreach (XmlElement xElement in XmlDoc.DocumentElement)
            {
                if (xElement.Name == "connectionStrings")
                {
                    xElement.FirstChild.Attributes[1].Value = connec;
                }
            }
            XmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
            XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
        }

        #endregion

        private void buttonLamMoi_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                txtlogin.Clear();
                txtpass.Clear();
                cboserverName.SelectedIndex = -1;
                //cboDataBase.SelectedIndex = -1;
            }
            catch (Exception)
            {
            }
        }

        private void buttonDong_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.Close();
            }
            catch(Exception)
            {
            }
        }     
    }
}

